package vista.paneles;

import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.Point;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.geom.Point2D;
import java.io.IOException;

import javax.swing.JButton;
import javax.swing.JPanel;
import javax.swing.JTextField;



import modelo.mapeado.Coordinate;
import modelo.mapeado.CoordinateRangeException;

import controlador.Controlador;

public class SearchPanel extends JPanel {

	private JTextField busqueda;
	private JButton buscar;
	private SearchListener oyenteBusqueda;
	private Controlador controlador;
	private KeyMap keyMap;
	private MapPanel mapa;
	
	public SearchPanel(Controlador control,MapPanel map) {
		
		setLayout(new FlowLayout(FlowLayout.CENTER));
		controlador = control;
		mapa = map;
		busqueda = new JTextField();
		busqueda.setPreferredSize(new Dimension(400,25));
		buscar = new JButton("Buscar");
		oyenteBusqueda = new SearchListener();
		buscar.addActionListener(oyenteBusqueda);
		keyMap = new KeyMap();
		busqueda.addKeyListener(keyMap);
		add(busqueda);
		add(buscar);
	}
	
	class SearchListener implements ActionListener {

		public void actionPerformed(ActionEvent e) {
			
			String direccion = busqueda.getText();
			if (direccion.equals(""))
				System.out.println("Dibujar panel error");
			else  {
				try {
					Coordinate coordenadas = new Coordinate(direccion);
					Point position = mapa.computePosition(new Point2D.Double
							(coordenadas.getLongitude(),coordenadas.getLatitude()));
					mapa.setCenterPosition(position);
					mapa.repaint();
				} catch (IOException e1) {
					e1.printStackTrace();
				}
				controlador.borrarDatos();
			}
		}
	}
	
	class KeyMap implements KeyListener {
		
		public void keyPressed(KeyEvent e) {
				
			if (e.getKeyCode() == KeyEvent.VK_ENTER) {
				String direccion = busqueda.getText();
				if (direccion.equals(""))
					System.out.println("Dibujar panel error");
				else  {
					try {
						Coordinate coordenadas = new Coordinate(direccion);
						Point position = mapa.computePosition(new Point2D.Double
								(coordenadas.getLongitude(),coordenadas.getLatitude()));
						mapa.setCenterPosition(position);
						mapa.repaint();
					} catch (IOException e1) {
						e1.printStackTrace();
					}
					controlador.borrarDatos();
				
				}
			}
		}
		
		public void keyTyped(KeyEvent e) {
			
		}

		public void keyReleased(KeyEvent e) {
			
		}
	}
	
}
